﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;

namespace HFController
{
    /// <summary>
    /// 用户逻辑业务
    /// </summary>
    public class UserController:ControllerBase
    {
        //单列
        private static UserController _userController;
        //实例化单列
        public static UserController getController()
        {
            if (_userController == null)
            {
                _userController = new UserController();
            }
            return _userController;
        }
        #region 用户

        /// <summary>
        /// 用户数据库访问
        /// </summary>
        private hf.DAL.User UserDAL = new hf.DAL.User();

        /// <summary>
        /// 找回密码
        /// </summary>
        /// <param name="uid"></param>
        /// <param name="typeid"></param>
        /// <returns></returns>
        public HFModel.ResultModel FindPassword(string uid, string typeid)
        {
            HFModel.ResultModel result = new HFModel.ResultModel();
            string EmailAddress = "";
            int total = 0;
            string password = "hf2234";
            if (typeid == "0")
            { 
                //
                List<hf.Model.User> list =  new hf.DAL.User().GetUserList(1 , 1, "UID='" + uid + "'" ,out total);
                if (list.Count == 0)
                {
                    List<hf.Model.Lawyer> list2 = new hf.DAL.Lawyer().GetLawyerList(1, 1, "UID='" + uid + "'", out total);
                    if (list2.Count == 0)
                    {
                        result.isTrue = false;
                        result.Message = "系统无法找到您的帐号，是否还未注册？";
                        return result;
                    }
                    else
                    {
                        EmailAddress = list2[0].Email;
                        list2[0].PWD = password;
                        new hf.DAL.Lawyer().Update(list2[0]);
                    }
                }
                else {
                    EmailAddress = list[0].Email;
                    list[0].PWD = password;
                    new hf.DAL.User().Update(list[0]);
                }
            }
            else {
                List<hf.Model.User> list = new hf.DAL.User().GetUserList(1, 1, "Email='" + uid + "'", out total);
                if (list.Count == 0)
                {
                    List<hf.Model.Lawyer> list2 = new hf.DAL.Lawyer().GetLawyerList(1, 1, "Email='" + uid + "'", out total);
                    if (list2.Count == 0)
                    {
                        result.isTrue = false;
                        result.Message = "系统无法找到您的帐号，是否还未注册？";
                        return result;
                    }
                    else
                    {
                        EmailAddress = list2[0].Email;
                        list2[0].PWD = password;
                        new hf.DAL.Lawyer().Update(list2[0]);
                    }
                }
                else
                {
                    EmailAddress = list[0].Email;
                    list[0].PWD = password;
                    new hf.DAL.User().Update(list[0]);
                }
            }

            string EmailBody = "<span color=\"red\">尊敬的用户</span>，您在红法网的帐号密码已经被初始化为：<span color=\"red\">\"" + password + "\" </span>,请躲闪保管<br /><br /><br /><br />红法网全体工作人员敬上！";
            LLL.EmailSender emailSender = new LLL.EmailSender("smtp.163.com", "publiclll", "800208", "publiclll@163.com", true);

            if (emailSender.SendEmail("红发网密码找回邮件", EmailBody, EmailAddress))
            {
                //这里是发送Email的API调用
                result.isTrue = true;
                result.Message = "一封包含您密码信息的邮件已经发送到您的邮箱，请注意查收。\n\n 如果收件箱里没有邮件，请查看垃圾邮件。";
            }
            else {
                result.isTrue = false;
                result.Message = emailSender.getErrorMessage();
            }
            return result;
        }

        /// <summary>
        /// 根据ID 得到一条用户列表
        /// </summary>
        /// <param name="ID"></param>
        /// <returns></returns>
        public hf.Model.User getUserModel(int ID)
        {
            hf.Model.User model = new hf.Model.User();
            int total;

            List<hf.Model.User> list = UserDAL.GetUserList(1, 1, "ID=" + ID.ToString(), out total);

            if (list.Count > 0)
            {
                model = list[0];
            }
            else
            {
                model = null;
            }
            return model;
        }

        /// <summary>
        /// 得到用户列表
        /// </summary>
        /// <param name="PagerStr"></param>
        /// <returns></returns>
        public List<hf.Model.User> getUserList(out string PagerStr)
        {
            List<hf.Model.User> list = new List<hf.Model.User>();

            //没有显示记录
            int PageSize = 10;
            //当前页码
            int PageNumber = 1;
            if (HttpContext.Current.Request.QueryString["Page"] != null)
            {
                PageNumber = int.Parse(HttpContext.Current.Request.QueryString["Page"].ToString());
            }
            //记录总条数
            int total;
            //筛选条件
            string strSql = "";

            //获得列表
            list = UserDAL.GetUserList(PageSize, PageNumber, strSql, out total);

            //分页
            PagerStr = LLL.Pager.TrunPageHtmlCode(PageSize, PageNumber, total, "");

            return list;
        }

        /// <summary>
        /// 验证用户名是否被使用
        /// </summary>
        /// <param name="UID"></param>
        /// <returns></returns>
        public bool GetUserByUID(string UID)
        {
            int PageSize = 1;
            int PageNumber = 1;
            int total = 0; 

            List<hf.Model.User> list = new List<hf.Model.User>();

            hf.DAL.Lawyer LawyerDAL = new hf.DAL.Lawyer();
            List<hf.Model.Lawyer> list1 = new List<hf.Model.Lawyer>();

            list = UserDAL.GetUserList(PageSize, PageNumber, "UID='" + UID + "'", out total);
            list1 = LawyerDAL.GetLawyerList(PageSize, PageNumber, "UID='" + UID + "'", out total);
            bool isUser = false;
            if (list.Count > 0 || list1.Count > 0)
            {
                isUser = true;
            }

            return isUser;
        }
        
        /// <summary>
        /// 用户注册
        /// </summary>
        /// <param name="UID"></param>
        /// <param name="PWD"></param>
        /// <param name="PWD1"></param>
        /// <param name="Email"></param>
        public HFModel.ResultModel doAddUser(string UID, string PWD, string PWD1, string Email)
        {
            HFModel.ResultModel result = new HFModel.ResultModel();
            hf.Model.User model = new hf.Model.User();
            //验证帐号是否被试用
            if (GetUserByUID(UID))
            {
                result.isTrue = false;
                result.goUrl = "history.go(-1);";
                result.historyUrl = "history.go(-1);";
                result.Message = "帐号被使用，请重新选择！";
                //this.doResult(result);
                //return;
            }
            else
            {
                //验证两次密码输入是否一致
                if (PWD != PWD1)
                {
                    result.isTrue = false;
                    result.goUrl = "history.go(-1);";
                    result.historyUrl = "history.go(-1);";
                    result.Message = "两次输入的密码不一致！";
                }
                else
                {
                    model.UID = UID;
                    model.PWD = PWD;
                    model.Email = Email;
                    model.Point = 0;
                    model.ProvinceID = 1;
                    model.CityID = 1;
                    model.RealName = "";
                    model.Addtime = DateTime.Now;
                    model.Content = "暂无自我介绍... ...";

                    try
                    {
                        model.ID = UserDAL.Add(model);

                        result.isTrue = true;
                        result.Message = "注册成功！";
                        result.historyUrl = "history.go(-1)";
                        HttpContext.Current.Session["User"] = model;
                    }
                    catch (Exception err)
                    {
                        result.isTrue = false;
                        result.Message = err.Message;
                        result.goUrl = "history.go(-1)";
                        result.historyUrl = "history.go(-1)";
                    }
                }
            }
            return result;
        }

        /// <summary>
        /// 注册用户
        /// </summary>
        /// <param name="UID"></param>
        /// <param name="PWD"></param>
        /// <param name="PWD1"></param>
        /// <param name="Email"></param>
        /// <param name="Point"></param>
        /// <param name="ProvinceID"></param>
        /// <param name="CityID"></param>
        /// <param name="RealName"></param>
        /// <param name="Addtime"></param>
        /// <param name="Content"></param>
        /// <param name="lblNum"></param>
        public void doAddUser(string UID, string PWD, string PWD1, string Email, int Point, int ProvinceID, int CityID, string RealName, string Content, string lblNum)
        {
            HFModel.ResultModel result = new HFModel.ResultModel();
            hf.Model.User model = new hf.Model.User();
            //验证帐号是否被试用
            if (GetUserByUID(UID))
            {
                result.isTrue = false;
                result.goUrl = "history.go(-1);";
                result.historyUrl = "history.go(-1);";
                result.Message = "帐号被使用，请重新选择！";
                this.doResult(result);
                return;
            }
            //验证两次密码输入是否一致
            if (PWD != PWD1)
            {
                result.isTrue = false;
                result.goUrl = "history.go(-1);";
                result.historyUrl = "history.go(-1);";
                result.Message = "两次输入的密码不一致！";
                this.doResult(result);
                return;
            }
            //判断验证码
            if (String.Compare(this.geCheckCookiesNum(), lblNum.Trim(), true) != 0)
            {
                result.isTrue = false;
                result.goUrl = "history.go(-1);";
                result.historyUrl = "history.go(-1);";
                result.Message = "验证码不正确！";
                this.doResult(result);
                return;
            }

            model.UID = UID;
            model.PWD = PWD;
            model.Email = Email;
            model.Point = 0;
            model.ProvinceID = ProvinceID;
            model.CityID = CityID;
            model.RealName = RealName;
            model.Addtime = DateTime.Now;
            model.Content = Content;

            try
            {
                model.ID = UserDAL.Add(model);

                result.isTrue = true;
                result.Message = "注册成功！";
                //  result.goUrl = "location='AdClass.aspx';";
                result.historyUrl = "history.go(-1)";
            }
            catch
            {
                result.isTrue = false;
                result.Message = "系统问题，清联系管理员";
                result.goUrl = "history.go(-1)";
                result.historyUrl = "history.go(-1)";
            }
            this.doResult(result);
        }

        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="UID"></param>
        /// <param name="PWD"></param>
        /// <returns></returns>
        public HFModel.ResultModel doUserLogin_ForAjax(string UID, string PWD ,string isRem)
        {
            HFModel.ResultModel result = new HFModel.ResultModel();

            int PageSize = 1;
            int PageNumber = 1;
            int total = 0;

            List<hf.Model.User> list = new List<hf.Model.User>();
            List<hf.Model.Lawyer> list2 = new List<hf.Model.Lawyer>();
            list2 = LawyerController.getController().getLawyerList(PageSize, PageNumber, "UID='" + UID + "' and PWD='" + PWD + "'", out total);
            list = UserDAL.GetUserList(PageSize, PageNumber, "UID='" + UID + "' and PWD='" + PWD + "'", out total);
            if (list.Count > 0)
            {
                result.isTrue = true;
                result.historyUrl = "history.go(-1);";
                result.Message = list[0].UID + "|" + list[0].Point.ToString();
                HttpContext.Current.Session["User"] = list[0];

                if (isRem == "1")
                {
                    HttpContext.Current.Response.Cookies["username"].Value = UID;
                    HttpContext.Current.Response.Cookies["username"].Expires = DateTime.Now.AddDays(1);
                    HttpContext.Current.Response.Cookies["password"].Value = PWD;
                    HttpContext.Current.Response.Cookies["password"].Expires = DateTime.Now.AddDays(1);
                    HttpContext.Current.Response.Cookies["isrember"].Value = isRem;
                    HttpContext.Current.Response.Cookies["isrember"].Expires = DateTime.Now.AddDays(1);
                }
                else {
                    HttpContext.Current.Response.Cookies["username"].Expires = DateTime.Now.AddDays(-2);
                    HttpContext.Current.Response.Cookies["password"].Expires = DateTime.Now.AddDays(-2);
                    HttpContext.Current.Response.Cookies["isrember"].Expires = DateTime.Now.AddDays(-2);
                    HttpContext.Current.Response.Cookies.Clear();
                }
            }
            else if (list2.Count > 0)
            {
                result.isTrue = true;
                result.historyUrl = "history.go(-1);";
                result.Message = list2[0].UID + "|" + list2[0].Point.ToString();
                HttpContext.Current.Session["Lawyer"] = list2[0];

                if (isRem == "1")
                {
                    HttpContext.Current.Response.Cookies["username"].Value = UID;
                    HttpContext.Current.Response.Cookies["username"].Expires = DateTime.Now.AddDays(1);
                    HttpContext.Current.Response.Cookies["password"].Value = PWD;
                    HttpContext.Current.Response.Cookies["password"].Expires = DateTime.Now.AddDays(1);
                    HttpContext.Current.Response.Cookies["isrember"].Value = isRem;
                    HttpContext.Current.Response.Cookies["isrember"].Expires = DateTime.Now.AddDays(1);
                }
                else
                {
                    HttpContext.Current.Response.Cookies["username"].Expires = DateTime.Now.AddDays(-2);
                    HttpContext.Current.Response.Cookies["password"].Expires = DateTime.Now.AddDays(-2);
                    HttpContext.Current.Response.Cookies["isrember"].Expires = DateTime.Now.AddDays(-2);
                    HttpContext.Current.Response.Cookies.Clear();
                }
            }
            else
            {
                result.isTrue = false;
                result.goUrl = "history.go(-1);";
                result.historyUrl = "history.go(-1);";
                result.Message = "登录失败，请检查用户名密码是否正确";
            }
            return result;
        }

        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="UID"></param>
        /// <param name="PWD"></param>
        public void doUserLogin(string UID, string PWD)
        {
            HFModel.ResultModel result = new HFModel.ResultModel();

            int PageSize = 1;
            int PageNumber = 1;
            int total = 0;

            List<hf.Model.User> list = new List<hf.Model.User>();
            list = UserDAL.GetUserList(PageSize, PageNumber, "UID='" + UID + "' and PWD='" + PWD + "'", out total);
            if (list.Count > 0)
            {
                result.isTrue = true;
                //   result.goUrl = "location='usermanage.aspx'";
                result.historyUrl = "history.go(-1);";
                result.Message = "登录成功！";
                HttpContext.Current.Session["User"] = list[0];
            }
            else
            {
                result.isTrue = false;
                result.goUrl = "history.go(-1);";
                result.historyUrl = "history.go(-1);";
                result.Message = "登录失败，请检查用户名密码是否正确";
            }
        }
        /// <summary>
        /// 修改资料，前台用
        /// </summary>
        /// <param name="realname"></param>
        /// <param name="email"></param>
        /// <param name="province"></param>
        /// <param name="cityid"></param>
        /// <param name="content"></param>
        /// <returns></returns>
        public HFModel.ResultModel doModifyUserInfo(string realname, string email, string province, string cityid, string content)
        {
            BagePages bp = new BagePages();
            HFModel.ResultModel result = new HFModel.ResultModel();
            if (bp.getLoginAccount() != null)
            {
                hf.Model.User model = bp.getLoginAccount();
                model.RealName = realname;
                model.Email = email;
                model.ProvinceID = int.Parse(province);
                model.CityID = int.Parse(cityid);
                model.Content = content;
                UserDAL.Update(model);
                result.isTrue = true;
                result.Message = "修改成功！";
            }
            else
            {
                result.isTrue = false;
                result.Message = "错误。未登录！";
            }
            return result;
        }

        /// <summary>
        /// 前台用，修改当前用户密码
        /// </summary>
        /// <param name="OldPWD"></param>
        /// <param name="PWD"></param>
        /// <returns></returns>
        public HFModel.ResultModel doModifyUserPWD(string OldPWD, string PWD)
        {
            BagePages bp = new BagePages();
            HFModel.ResultModel result = new HFModel.ResultModel();
            if(bp.getLoginAccount() != null)
            {
                hf.Model.User model = bp.getLoginAccount();
                if (model.PWD != OldPWD)
                {
                    result.isTrue = false;
                    result.Message = "当前密码错误";
                }
                else {
                    model.PWD = PWD;
                    UserDAL.Update(model);
                    result.isTrue = true;
                    result.Message = "修改成功，请牢记密码！";
                }
            }else{
                result.isTrue = false;
                result.Message = "错误。未登录！";
            }
            return result;
        }
        /// <summary>
        /// 修改用户信息
        /// </summary>
        /// <param name="ID"></param>
        /// <param name="Email"></param>
        /// <param name="ProvinceID"></param>
        /// <param name="CityID"></param>
        /// <param name="RealName"></param>
        /// <param name="Content"></param>
        public void doModifyUser(int ID,string UID,string PWD, string Email,int Point, int ProvinceID, int CityID, string RealName, string Content)
        {
            HFModel.ResultModel result = new HFModel.ResultModel();
            hf.Model.User model = this.getUserModel(ID);

            model.UID = UID;
            model.PWD = PWD;
            model.Email = Email;
            model.Point = Point;
            model.ProvinceID = ProvinceID;
            model.CityID = CityID;
            model.RealName = RealName;
            model.Content = Content;

            try
            {
                //执行修改
                UserDAL.Update(model);

                result.isTrue = true;
                result.Message = "修改成功！";
              //  result.goUrl = "location='UserList.aspx';";
                result.historyUrl = "history.go(-1)";
            }
            catch
            {
                result.isTrue = false;
                result.Message = "系统问题，清联系管理员";
                result.goUrl = "history.go(-1)";
                result.historyUrl = "history.go(-1)";
            }
            this.doResult(result);
        }
        /// <summary>
        /// 管理员添加用户
        /// </summary>
        /// <param name="UID"></param>
        /// <param name="PWD"></param>
        /// <param name="Email"></param>
        /// <param name="Point"></param>
        /// <param name="ProvinceID"></param>
        /// <param name="CityID"></param>
        /// <param name="RealName"></param>
        /// <param name="Content"></param>
        public void doAdminAddUser(string UID, string PWD, string Email, int Point, int ProvinceID, int CityID, string RealName, string Content)
        {
            HFModel.ResultModel result = new HFModel.ResultModel();
            hf.Model.User model = new hf.Model.User();
            //验证帐号是否被试用
            if (GetUserByUID(UID))
            {
                result.isTrue = false;
                result.goUrl = "history.go(-1);";
                result.historyUrl = "history.go(-1);";
                result.Message = "帐号被使用，请重新选择！";
                this.doResult(result);
                return;
            }
            model.UID = UID;
            model.PWD = PWD;
            model.Email = Email;
            model.Point = Point;
            model.ProvinceID = ProvinceID;
            model.CityID = CityID;
            model.RealName = RealName;
            model.Addtime = DateTime.Now;
            model.Content = Content;

            try
            {
                model.ID = UserDAL.Add(model);

                result.isTrue = true;
                result.Message = "添加成功！";
                result.goUrl = "location='User.aspx';";
                result.historyUrl = "history.go(-1)";
            }
            catch
            {
                result.isTrue = false;
                result.Message = "系统问题，清联系管理员";
                result.goUrl = "history.go(-1)";
                result.historyUrl = "history.go(-1)";
            }
            this.doResult(result);
        }

        /// <summary>
        /// 管理员修改用户资料
        /// </summary>
        /// <param name="ID"></param>
        /// <param name="Email"></param>
        /// <param name="Point"></param>
        /// <param name="ProvinceID"></param>
        /// <param name="CityID"></param>
        /// <param name="RealName"></param>
        /// <param name="Content"></param>
        public void doAdminModifyUser(int ID,string UID,string PWD, string Email, int Point, int ProvinceID, int CityID, string RealName, string Content)
        {
            HFModel.ResultModel result = new HFModel.ResultModel();
            hf.Model.User model = this.getUserModel(ID);

            model.UID = UID;
            model.PWD = PWD;
            model.Email = Email;
            model.Point = Point;
            model.ProvinceID = ProvinceID;
            model.CityID = CityID;
            model.RealName = RealName;
            model.Content = Content;

            try
            {
                //执行修改
                UserDAL.Update(model);

                result.isTrue = true;
                result.Message = "修改成功！";
                result.goUrl = "location='UserManageList.aspx';";
                result.historyUrl = "history.go(-1)";
            }
            catch
            {
                result.isTrue = false;
                result.Message = "系统问题，清联系管理员";
                result.goUrl = "history.go(-1)";
                result.historyUrl = "history.go(-1)";
            }
            this.doResult(result);
        }

        /// <summary>
        /// 修改用户密码
        /// </summary>
        /// <param name="ID"></param>
        /// <param name="oldPWD"></param>
        /// <param name="PWD"></param>
        /// <param name="PWD1"></param>
        public void doModifyUserPWD(int ID, string oldPWD, string PWD, string PWD1)
        {
            HFModel.ResultModel result = new HFModel.ResultModel();
            hf.Model.User model = this.getUserModel(ID);

            if (oldPWD != model.PWD)
            {
                result.isTrue = false;
                result.goUrl = "history.go(-1)";
                result.historyUrl = "history.go(-1)";
                result.Message = "当前密码错误";
                doResult(result);
            }
            else if (PWD != PWD1)
            {
                result.isTrue = false;
                result.goUrl = "history.go(-1)";
                result.historyUrl = "history.go(-1)";
                result.Message = "两次输入密码不一致";
                doResult(result);
            }
            else
            {
                model.PWD = PWD;

                UserDAL.Update(model);
                result.isTrue = true;
                //     result.goUrl = "location='../main.aspx'";
                result.historyUrl = "history.go(-1);";
                result.Message = "修改成功";
                doResult(result);
            }
        }


        /// <summary>
        /// 用户退出
        /// </summary>
        public void doLogout()
        {
            HttpContext.Current.Session["User"] = null;
            HttpContext.Current.Session.RemoveAll();
            HttpContext.Current.Response.Redirect("index.aspx");
        }

        /// <summary>
        /// 删除用户
        /// </summary>
        /// <param name="ID"></param>
        public void doDelegeUser(int ID)
        {
            HFModel.ResultModel result = new HFModel.ResultModel();

            try
            {
                UserDAL.Delete(ID);

                result.isTrue = true;
                result.Message = "删除成功！";
                result.goUrl = "location='UserList.aspx';";
                result.historyUrl = "history.go(-1)";
            }
            catch
            {
                result.isTrue = false;
                result.Message = "系统问题，清联系管理员";
                result.goUrl = "history.go(-1)";
                result.historyUrl = "history.go(-1)";
            }
            this.doResult(result);
        }

        /// <summary>
        /// 批量删除用户
        /// </summary>
        /// <param name="IDS"></param>
        public void doDelegeUser(string[] IDS)
        {
            HFModel.ResultModel result = new HFModel.ResultModel();
            try
            {
                for (int i = 0; i < IDS.Length; i++)
                {
                    UserDAL.Delete(int.Parse(IDS[i].Trim()));
                }
                result.isTrue = true;
                result.Message = "删除成功！";
                result.goUrl = "location='UserList.aspx';";
                result.historyUrl = "history.go(-1)";
            }
            catch
            {
                result.isTrue = false;
                result.Message = "系统问题，清联系管理员";
                result.goUrl = "history.go(-1)";
                result.historyUrl = "history.go(-1)";
            }
            this.doResult(result);
        }
        #endregion
    }
}
